package com.terry.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;

public class ClientHandler extends ChannelInboundHandlerAdapter {

	private EventLoopGroup workerGroup;
	private Object msg;
	public ClientHandler(EventLoopGroup workerGroup) {
		this.workerGroup = workerGroup;
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			ByteBuf bb = (ByteBuf)msg;
			int length = bb.readableBytes();
			byte[] r = new byte[length];
			bb.readBytes(r);
			System.out.println(new String(r));
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			this.workerGroup.shutdownGracefully();
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("GET /user/get HTTP/1.1\r\n");
		sb.append("Host: localhost:8000\r\n");
		sb.append("\r\n\r\n");
		ByteBuf bb = ctx.alloc().buffer(sb.length());
		System.out.println(sb.toString());
		bb.writeBytes(sb.toString().getBytes());
		ctx.write(bb);
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		super.exceptionCaught(ctx, cause);
	}

}
